using System;
namespace ArduinoInterOp
{
    public delegate void PinValueChangedEventHandler(ArduinoPinValueData sender, PinValueChangedEventArgs args);

    public class PinValueChangedEventArgs
    {
        public ushort LastValue { get; internal set; }
    }

    public class ArduinoPinValueData
    {
        private readonly ArduinoPinsManager _manager;
        private PinValueChangedEventHandler _valueChangedHandler;

        internal ArduinoPinValueData(byte pin, ArduinoPinsManager manager)
        {
            ChangeDelta = 1;
            Pin = pin;
            _manager = manager;
        }

        public byte Pin { get; private set; }
        public ushort Value { get; internal set; }
        public long LastModifiedInTicks { get; internal set; }

        internal int ChangeDelta { get; set; }

        public event PinValueChangedEventHandler ValueChanged
        {
            add
            {
                _valueChangedHandler += value;

                if(_valueChangedHandler != null)
                {
                    _manager.NotifyPinHasHandlers(this.Pin);                    
                }
            }
            remove
            {
                if (_valueChangedHandler != null && value != null) _valueChangedHandler -= value;

                if (_valueChangedHandler == null)
                {
                    _manager.NotifyPinHasNoHandlers(this.Pin);
                }
            }
        }

        internal void OnValueChanged(PinValueChangedEventArgs e)
        {
            var handler = _valueChangedHandler;
            if (handler != null) handler(this, e);
        }
    }
}